<?php

function format_cell($time, $value) {
  // Get max fail rate for proxy
  $sql = "select * from core_config where name = 'valid_proxy_fail_rate'";
  $ret = sql_or_die($sql);
  $row = mysql_fetch_assoc($ret);
  $max_rate = $row['value'];

  $val = explode(',', $value);
  if (trim($val[2]) > $max_rate * 100) {
    return "<span style='color: red'>$time <br /> $value<span>";
  } else  if (trim($val[2]) < 5) {
    return "<span style='color: #00CC00'>$time <br /> $value<span>";
  } else {
    return "$time <br /> $value";
  }

}

function draw_table($table, $limit) {
  $content = "";
  foreach($table as $proxy) {
    $cur = "<td>" . $proxy['addr'] . "</td>";
    foreach($proxy['data'] as $data) {
      $time = date('Y-m-d', strtotime($data['collect_date']));
      $value = sprintf("%d, %d, %.2f%%", $data['use_count'], $data['fail_count'], $data['fail_count'] / $data['use_count'] * 100);
      $cur .= "<td>" . format_cell($time, $value) . "</td>";
    }
    $content .= "<tr>" . $cur . "</tr>";
  }
  echo "<table border='1' id='stat-table' cellspacing='0' cellpadding='0'>" . $content . "</table>";
}

function show_raw($limit) {
  $sql = "select addr, slot_id from proxy order by slot_id";
  $ret = mysql_query($sql);
  if (!$ret) {
    die("($sql) failed:" . mysql_error());
  }
  echo mysql_num_rows($ret) . " proxies in log <br />";
  $table = array();
  while ($proxy = mysql_fetch_assoc($ret)) {
    $addr = $proxy['addr'];
    $slot = $proxy['slot_id'];
    $sql = "select * from proxy_log where proxy_ip = '$addr' order by collect_date desc limit $limit";
    $stat_ret = mysql_query($sql);
    if (!$ret) {
      die("($sql) failed:" . mysql_error());
    }
    $row = array();
    if ($slot != NULL) {
      $row['addr'] = "<span style='background-color: #66FF99'> $addr . ({$slot}) </span>";
    } else {
      $row['addr'] = "<span> $addr </span>";
    }
    $row['data'] = array();
    while($data = mysql_fetch_assoc($stat_ret)) {
      $row['data'][] = $data;
    }
    $table[] = $row;
  }

  draw_table($table, $limit);
}

require_once '../util.php';
require_once '../config.php';
connect_db();
show_raw(10);

?>


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="/lib/js/jquery.js"></script>
    <script type="text/javascript" src="/lib/js/jquery.form.js"></script>
    <script type="text/javascript" src="/lib/js/sprintf.js"></script>
    <link rel="stylesheet" type="text/css" href="/lib/css/reset.css" />
    <link rel="stylesheet" type="text/css" href="css/proxy.css" />

    <title>Proxy Failure Stats | See how what crap you have bought</title>
  </head>

  <body>
   <div id="main">
   </div>
  </body>
</html>
